import { defineStore } from 'pinia'

export const useHistoryStore = defineStore('history', {
  state: () => ({
    past: [],
    future: [],
    maxHistory: 20,
    current: null
  }),

  getters: {
    canUndo: (state) => state.past.length > 0,
    canRedo: (state) => state.future.length > 0
  },

  actions: {
    addState(state) {
      if (this.current && JSON.stringify(this.current) === JSON.stringify(state)) {
        return
      }
      
      if (this.current) {
        this.past.push(JSON.stringify(this.current))
      }
      if (this.past.length > this.maxHistory) {
        this.past.shift()
      }
      this.current = state
      this.future = []
    },

    undo() {
      if (!this.canUndo) return null
      if (this.current) {
        this.future.push(JSON.stringify(this.current))
      }
      const previousState = this.past.pop()
      if (previousState) {
        this.current = JSON.parse(previousState)
        return this.current
      }
      this.current = { nodes: [], connections: [] }
      return this.current
    },

    redo() {
      if (!this.canRedo) return null
      const nextState = this.future.pop()
      if (nextState) {
        if (this.current) {
          this.past.push(JSON.stringify(this.current))
        }
        this.current = JSON.parse(nextState)
        return this.current
      }
      return null
    }
  }
}) 